package com.wlz.file;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author wlz
 * @date 2022-11-03  4:12 下午
 */
public class FileCopyStreamTest {

    public static void main(String[] args) throws Exception{
//        String fullPath = "/Users/wlz/Desktop/HUMTEST_30-40.zip";
//        testSize(fullPath);
        long time = System.currentTimeMillis();
        String fullPath = "/Users/wlz/Desktop/ESC008.zip";
        String destPackagePath = fullPath.substring(0, fullPath.lastIndexOf("."));
        File destFilePath = new File(destPackagePath);
        if (!destFilePath.exists()) {
            destFilePath.mkdirs();
        }
        copyFileUsingFileStream(new File(fullPath), new File(destPackagePath + fullPath.substring(fullPath.lastIndexOf("/"))));
        System.out.println("time : " + (System.currentTimeMillis() - time));
    }

    public static void testSize(String fullPath) {
        File file = new File(fullPath);
        int bufferSize = 1024*1024;
        long size = file.length();
        long lastCount = size % bufferSize;
        long count = size/bufferSize;
        System.out.println(count);
        System.out.println(lastCount);
    }


    public static void copyFileUsingFileStream(File source, File original) throws IOException {
        FileInputStream input = null;
        FileOutputStream output = null;
        int bufferSize = 1024*1024;
        try {
            long size = source.length();
            long lastbufferSize = (size % bufferSize);
            long count =  (size/bufferSize);

            input = new FileInputStream(source);
            output = new FileOutputStream(original);
            byte[] buffer = new byte[bufferSize];
            int len = 0;
            while(((len = input.read(buffer)) != -1) && count > 0) {
                output.write(buffer);
                count--;
            }
            if (lastbufferSize > 0) {
                byte[] lastBuffer = new byte[(int) lastbufferSize];
                while ((len = input.read(lastBuffer)) != -1) {
                    output.write(lastBuffer);
                }
            }
        }finally {
            if(input != null) {
                input.close();
            }
            if(output != null) {
                output.close();
            }
        }
    }
}
